package com.shuo.map;

import java.util.LinkedHashMap;
import java.util.Set;

/**
 * 1. LinkedHashMap就是在HashMap的基础上多维护了条链表即head和tail
 * 2. 在HashMap的Node基础上进行扩展得到Entry, 也只是增加了before和after属性
 */
public class LinkedHashMapTest {

    public static void main(String[] args) {
        accessOrder0();
    }

    public static void insertOrder() {
        // 默认是插入顺序
        LinkedHashMap<Integer, String> insertOrder = new LinkedHashMap<>();
        String value = "shuoGG";
        int i = 0;
        insertOrder.put(i++, value);
        insertOrder.put(i++, value);
        insertOrder.put(i++, value);
        insertOrder.put(i++, value);
        insertOrder.put(i++, value);
        //遍历
        Set<Integer> set = insertOrder.keySet();
        for (Integer s : set) {
            String mapValue = insertOrder.get(s);
            System.out.println(s + "---" + mapValue);
        }
    }

    public static void accessOrder() {
        // 设置为访问顺序的方式
        LinkedHashMap<Integer, String> accessOrder = new LinkedHashMap<>(16, 0.75f, true);
        String value = "shuoGG";
        int i = 0;
        accessOrder.put(i++, value);
        accessOrder.put(i++, value);
        accessOrder.put(i++, value);
        accessOrder.put(i++, value);
        accessOrder.put(i++, value);
        // 访问一下key为3的元素再进行遍历
        accessOrder.get(3);
        // 遍历
        Set<Integer> sets = accessOrder.keySet();
        for (Integer key : sets) {
            System.out.println(key);
        }

    }

    /**
     * 该方法会抛异常:
     * 在AccessOrder的情况下，使用get方法也是结构性的修改
     */
    public static void accessOrder0() {
        // 设置为访问顺序的方式
        LinkedHashMap<Integer, String> accessOrder = new LinkedHashMap<>(16, 0.75f, true);
        String value = "shuoGG";
        int i = 0;
        accessOrder.put(i++, value);
        accessOrder.put(i++, value);
        accessOrder.put(i++, value);
        accessOrder.put(i++, value);
        accessOrder.put(i++, value);
        // 遍历
        Set<Integer> sets = accessOrder.keySet();
        for (Integer key : sets) {
            String mapValue = accessOrder.get(key);
            System.out.println(key + "---" + mapValue);
        }

    }
}
